package com.pronhub.cloud.shop.web.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.pronhub.cloud.shop.alipay.AlipayProperties;
import com.pronhub.cloud.shop.domain.OrderInfo;
import com.pronhub.cloud.shop.service.IOrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

/**
 * 支付功能的控制器
 */

@Controller
@RequestMapping("/pay")
public class PayController {
    //支付的接口  根据订单去实现支付
    @Autowired
    private AlipayClient alipayClient;
    //读取配置文件 从里面获得我们徐亚ode东西
    @Autowired
    private AlipayProperties alipayProperties;
    //根据商品的订单号找商品 然后找到价格之类的参数传给支付宝
    @Autowired
    private IOrderInfoService orderInfoService;
    //订单的支付Controller
    @RequestMapping("/payOrder")
    public void payOrder(String orderNo, HttpServletResponse response) throws Exception {
        OrderInfo orderInfo =   orderInfoService.find(orderNo);
        if(orderInfo==null){
            response.sendRedirect("http://localhost:/50x.html");
            return;
        }
        //支付宝支付，项目中可能有订单支付，会员支付，支付其他东西.
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());//同步回调

        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());//异步回调
//商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderInfo.getOrderNo();
        //付款金额，必填
        String total_amount = orderInfo.getSeckillPrice()+"" ;
        //订单名称，必填
        String subject = "秒杀商品-"+orderInfo.getGoodName();
        //商品描述，可空
        String body ="商品详情-"+orderInfo.getGoodName();
        //把前台的参数封装成JSON字符串
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //必须要有这句话，不然又问题.
        response.setContentType("text/html;charset=utf-8");

        //输出回去
        //得到输出流IO的谁管
        PrintWriter out = response.getWriter();
        out.print(result);
    }
    //支付宝回调的东西
    //1 异步回调函数
    @RequestMapping("/notify_url")
    @ResponseBody
    public String notifyUrl(@RequestParam Map<String,String> params) throws AlipayApiException {
        System.err.println("异步回调函数====>"+new Date());
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType()); //调用SDK验证签名
        //订单支付知否成功
        if (signVerified){
            String out_trade_no = params.get("out_trade_no");
            //在异步回调的时候，业务做了，但是在返回"success"的时候，支付宝没有收到响应请求.继续在
            // 发送请求.此方法有可能会被多次调用
            //做幂等性判断，会使用支付流水表来控制，防止业务重复执行.
            //我的理解
            //幂等性处理 当我们处理完的时候,支付宝可能还会往这里发送信息,积分等问题就会出现了 我们需要一个判断更改 改了MySql几行
            int count  = orderInfoService.changePayStatus(out_trade_no,OrderInfo.STATUS_ACCOUNT_PAID);
            if (count==0){
                //就是订单状态没改成功
                //在支付修改订单状态的时候，刚好已经超时取消订单了，订单状态是不能修改的。进行退款流程.
                //往MQ中发送消息，做退款操作，人工需要审核之后才进行退款操作.

            }
            //修改订单状态
            return "success";
        }else {
            return "fail";
        }
    }

    //同步回调
    @RequestMapping("/return_url")
    public void returnUrl(@RequestParam Map<String,String> params,HttpServletResponse response) throws AlipayApiException, IOException {
        System.err.println("同步回调====>"+new Date());
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType()); //调用SDK验证签名
        if (signVerified){
            //验证成功
            String out_trade_no = params.get("out_trade_no");
            response.sendRedirect("http://localhost/order_detail.html?orderNo="+out_trade_no);
        }else {
            response.sendRedirect("http://localhost/50x.html");
        }
    }
}
